package com.zh.javaguide.threadpool;

import java.util.Date;
import java.util.concurrent.*;

/**
 * Copyright (C) 广州中和互联网技术有限公司
 *
 * @author 范家微 fanjiawei@borche.cn
 * @date :2021/1/23 19:41
 */
public class ThreadPoolDemo1 {
	public static void main(String[] args) {

		//使用阿里巴巴推荐的方式创建线程池
		ThreadPoolExecutor executor = new ThreadPoolExecutor(
				5,
				10,
				1L,
				TimeUnit.SECONDS,
				new ArrayBlockingQueue<>(100),
				new ThreadPoolExecutor.CallerRunsPolicy()
		);
		for (int i = 0; i < 10; i++) {
			MyRunnable worker = new MyRunnable("线程" + i);
			executor.execute(worker);
		}
		// 终止线程池
		executor.shutdown();
		while (!executor.isTerminated()){

		}
		System.out.println("finished all threads");

	}
}


class MyRunnable implements Runnable {
	private String command;

	public MyRunnable(String s) {
		this.command = s;

	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " Start. Time = " + new Date());
		processCommand();
		System.out.println(Thread.currentThread().getName() + " End. Time = " + new Date());
	}


	private void processCommand(){
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return this.command;
	}

	/**
	 * 输出结果
	 * pool-1-thread-3 Start. Time = Sat Jan 23 20:20:20 CST 2021
	 * pool-1-thread-4 Start. Time = Sat Jan 23 20:20:20 CST 2021
	 * pool-1-thread-5 Start. Time = Sat Jan 23 20:20:20 CST 2021
	 * pool-1-thread-1 Start. Time = Sat Jan 23 20:20:20 CST 2021
	 * pool-1-thread-2 Start. Time = Sat Jan 23 20:20:20 CST 2021
	 *
	 * pool-1-thread-5 End. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-1 End. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-2 End. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-1 Start. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-2 Start. Time = Sat Jan 23 20:20:25 CST 2021
	 *
	 * pool-1-thread-4 End. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-5 Start. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-4 Start. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-3 End. Time = Sat Jan 23 20:20:25 CST 2021
	 * pool-1-thread-3 Start. Time = Sat Jan 23 20:20:25 CST 2021
	 *
	 * pool-1-thread-1 End. Time = Sat Jan 23 20:20:30 CST 2021
	 * pool-1-thread-5 End. Time = Sat Jan 23 20:20:30 CST 2021
	 * pool-1-thread-2 End. Time = Sat Jan 23 20:20:30 CST 2021
	 * pool-1-thread-4 End. Time = Sat Jan 23 20:20:30 CST 2021
	 * pool-1-thread-3 End. Time = Sat Jan 23 20:20:30 CST 2021
	 * finished all threads
	 *
	 * 结论：线程池每次会同时执⾏ 5 个任务，这 5 个任务执⾏
	 * 完之后，剩余的 5 个任务才会被执⾏
	 */
}
